package com.lujianfei.redpacketstat.ui

import android.app.AlertDialog
import android.content.DialogInterface
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.lifecycle.Observer
import com.lujianfei.redpacketstat.R
import com.lujianfei.redpacketstat.base.BaseActivity
import com.lujianfei.redpacketstat.databinding.ActivityUserBinding
import com.lujianfei.redpacketstat.ui.viewmodel.UserDetailViewModel
import org.koin.android.ext.android.inject

class UserDetailActivity : BaseActivity<ActivityUserBinding>() {

    companion object{
        const val key_user_id = "user_id"
    }

    private var userId:Int = 0
    private val viewModel:UserDetailViewModel by inject()

    override fun layoutId(): Int {
        return R.layout.activity_user
    }

    override fun initView() {
        dataBinding?.toolBar?.title = "详情"
        setSupportActionBar(dataBinding?.toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun initEvent() {
    }

    override fun initData() {
        val activityUserBinding = dataBinding as ActivityUserBinding
        viewModel.uiState.observe(this, Observer { state ->
            state.userEntity?.let { user ->
                activityUserBinding.user = user
            }

            state.redPacketEntity?.let { redpacket ->
                activityUserBinding.redpacket = redpacket
            }
            state.showToastString?.let {
                showToast(it)
                finish()
            }
            state.showDialog?.let {
                showConfirmDialog(it.title, it.message) {
                    it.callback(true)
                }
            }
        })
        activityUserBinding.viewModel = viewModel
        userId = intent.getIntExtra(key_user_id,0)
        viewModel.loadData(userId)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_user_detail, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            R.id.action_save->{
                viewModel.save() {
                    _,_ ->
                    finish()
                }
            }
            android.R.id.home->{
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    fun showConfirmDialog(title: String, message: String, callback: () -> Unit) {
        AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确认") { _: DialogInterface, _: Int ->
                callback()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    fun showToast(text:String) {
        Toast.makeText(this,text,Toast.LENGTH_SHORT).show()
    }
}